import React, { useState, useEffect } from 'react';
import { Table, Switch, Tag, message } from 'antd';
import { getUserList, enableUser } from '../api/user';

const UserManage: React.FC = () => {
  const [users, setUsers] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [switchLoading, setSwitchLoading] = useState<{[key: number]: boolean}>({});

  const fetchUsers = async (pageNum = 1, size = 10) => {
    setLoading(true);
    try {
      const res = await getUserList(pageNum, size);
      if (res.data && res.data.data && Array.isArray(res.data.data.records)) {
        setUsers(res.data.data.records);
        setTotal(res.data.data.total || 0);
      } else {
        setUsers([]);
        setTotal(0);
      }
    } catch (error) {
      message.error('获取用户列表失败');
    }
    setLoading(false);
  };

  const handleEnable = async (id: number, checked: boolean) => {
    setSwitchLoading(prev => ({ ...prev, [id]: true }));
    try {
      await enableUser(id, checked);
      setUsers(users.map(u => u.id === id ? { ...u, enableFlag: checked } : u));
      message.success(checked ? '已启用用户' : '已禁用用户');
    } catch (error) {
      message.error('操作失败');
    }
    setSwitchLoading(prev => ({ ...prev, [id]: false }));
  };

  useEffect(() => {
    fetchUsers(page, pageSize);
  }, [page, pageSize]);

  const columns = [
    { title: '账号', dataIndex: 'username', key: 'username' },
    { title: '昵称', dataIndex: 'nickname', key: 'nickname' },
    { 
      title: '状态', 
      dataIndex: 'enableFlag', 
      key: 'enableFlag', 
      render: (v: boolean) => v ? <Tag color="green">已启用</Tag> : <Tag color="red">已禁用</Tag> 
    },
    { 
      title: '操作', 
      key: 'action', 
      render: (_: any, record: any) => (
        <Switch 
          checked={record.enableFlag} 
          onChange={checked => handleEnable(record.id, checked)} 
          loading={switchLoading[record.id]}
        />
      ) 
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <h2>用户管理</h2>
      <Table 
        rowKey="id" 
        columns={columns} 
        dataSource={users} 
        loading={loading}
        pagination={{
          current: page,
          pageSize,
          total,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
    </div>
  );
};

export default UserManage; 